package middle;

public class Solution_114 {

    public void flatten(TreeNode root) {
        if (root == null) {
            return;
        }
        dps(root);
    }

    private TreeNode dps(TreeNode node) {
        if (node.left != null) {
            TreeNode temp = dps(node.left);
            temp.right = node.right;
            node.right = node.left;
            node.left = null;
        }
        TreeNode next = null;
        if (node.right != null) {
            next = dps(node.right);
        }
        return next != null ? next : node;
    }

    /*private TreeNode head = null;
    private TreeNode res = null;

    public void flatten(TreeNode root) {
        if (root==null) {
            return;
        }
        dps(root);
        root.right = head.right;
        root.left = null;
    }

    private void dps(TreeNode node) {
        if (node == null) {
            return;
        }
        if (res == null) {
            res = new TreeNode(node.val);
            head = res;
        } else {
            res.right = new TreeNode(node.val);
            res = res.right;
        }
        dps(node.left);
        dps(node.right);
    }*/

    public static void main(String[] args) {
        Solution_114 model = new Solution_114();
        TreeNode root = new TreeNode(1);
        root.left = new TreeNode(2);
        root.left.left = new TreeNode(3);
        root.left.right = new TreeNode(4);
        root.right = new TreeNode(5);
        root.right.right = new TreeNode(6);
        model.flatten(root);
        System.out.println(root);
    }

    static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
}
